package com.lzw.breezeNovel.webApp.service.impl.novel;

import com.lzw.breezeNovel.model.entity.pojo.novel.Book;
import com.lzw.breezeNovel.model.entity.pojo.novel.Chapter;
import com.lzw.breezeNovel.webApp.mapper.novel.ChapterMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.novel.ChapterService;
import com.lzw.breezeNovel.webApp.vo.novel.BookVo;
import com.lzw.breezeNovel.webApp.vo.novel.ChapterVo;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.novel.impl
 * @date 2025/3/2
 * @description 章节的服务实现类
 */
@Service
@SuppressWarnings("all")
public class ChapterServiceImpl implements ChapterService {

    /**
     * 注入mapper
     */
    @Autowired
    private ChapterMapper chapterMapper;
    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 根据bookId获取章节
     * @param bookId
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public BookVo getChaptersByBookId(Long bookId) {
        //根据bookId + userId获取章节
        Book books =  chapterMapper.selectByBookId(bookId);
        //进行数据的拷贝
        List<ChapterVo> chapterVos = Copy(books.getChapters());
        //设置章节数据
        BookVo bookVo = new BookVo();
        //进行对象拷贝
        BeanUtils.copyProperties(books, bookVo);
        //设置章节
        bookVo.setChapters(chapterVos);
        return bookVo;
    }

    /**
     * 数据拷贝
     * @param books
     * @return
     */
    @Nullable
    @Contract(pure = true)
    private List<ChapterVo> Copy(List<Chapter> chapters) {
        //判断是否有数据
        if (chapters == null || chapters.size() == 0) {
            return null;
        }
        //进行数据的拷贝
        return chapters.stream().map(chapter -> {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            //获取时间
            Date createTime = chapter.getCreateTime();
            // 转换为 LocalDateTime（Java 8 及以上）
            LocalDateTime localDateTime = createTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            // 定义格式化模式
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
            // 格式化时间
            String formattedTime = localDateTime.format(dateTimeFormatter);
            chapterVo.setCreateTime(formattedTime);
            return chapterVo;
        }).toList();
    }

}
